<template>
  <view class="rating-distribution-container">
    <!-- 顶部标题 -->
    <view class="header">
      <view class="title">评分分布分析</view>
      <view class="subtitle">{{analysisStore.timeRangeText}}图书评分分布情况</view>
    </view>
    
    <!-- 操作栏 -->
    <view class="action-bar">
      <view class="chart-type-switcher">
        <view 
          v-for="(item, index) in chartTypes" 
          :key="index" 
          :class="['type-item', analysisStore.filter.chartType === item.value ? 'active' : '']"
          @click="switchChartType(item.value)"
        >
          <text class="iconfont" :class="item.icon"></text>
          <text>{{item.label}}</text>
        </view>
      </view>
    </view>
    
    <!-- 评分总览卡片 -->
    <view class="overview-card">
      <view class="overview-item">
        <text class="item-value">{{totalRatings || '0'}}</text>
        <text class="item-label">评分总数</text>
      </view>
      <view class="overview-item">
        <text class="item-value">{{averageRating || '0.0'}}</text>
        <text class="item-label">平均评分</text>
      </view>
      <view class="overview-item">
        <text class="item-value">{{highestRatingPercentage}}%</text>
        <text class="item-label">{{highestRating}}星占比</text>
      </view>
    </view>
    
    <!-- 图表区域 -->
    <view class="chart-area" v-if="!isLoading">
      <!-- 使用图表组件显示评分分布数据 -->
      <qiun-data-charts 
        :type="chartType" 
        :chart-data="chartDataObject" 
        :loading="chartLoading"
        canvas-id="rating-chart"
        canvas-height="350px"
      ></qiun-data-charts>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-container" v-if="isLoading">
      <uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
    </view>
    
    <!-- 评分详情列表 -->
    <view class="rating-list" v-else>
      <view class="section-title">评分详情</view>
      
      <view 
        class="rating-item" 
        v-for="(item, index) in ratingDistribution" 
        :key="index"
      >
        <view class="rating-stars">
          <text class="star-value">{{item.rating}}</text>
          <text class="star-label">星</text>
          <uni-rate :value="item.rating" size="16" :readonly="true" :is-fill="true" color="#ff9900"></uni-rate>
        </view>
        
        <view class="rating-bar">
          <view 
            class="rating-progress" 
            :style="{width: item.percentage * 100 + '%'}"
          ></view>
        </view>
        
        <view class="rating-info">
          <text class="rating-count">{{item.count}}</text>
          <text class="rating-percentage">{{(item.percentage * 100).toFixed(1)}}%</text>
        </view>
      </view>
      
      <!-- 无数据提示 -->
      <view class="no-data" v-if="ratingDistribution.length === 0">
        <text>暂无评分数据</text>
      </view>
    </view>
    
    <!-- 底部操作区 -->
    <view class="footer-actions">
      <button class="action-btn export-btn" @click="exportData">
        <text class="iconfont icon-download"></text>
        <text>导出数据</text>
      </button>
      <button class="action-btn refresh-btn" @click="refreshData">
        <text class="iconfont icon-refresh"></text>
        <text>刷新</text>
      </button>
    </view>
  </view>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import QiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue';
import { useAnalysisStore } from '@/store/analysis.js';

export default {
  name: 'RatingDistribution',
  components: {
    QiunDataCharts
  },
  setup() {
    // 获取分析数据仓库
    const analysisStore = useAnalysisStore();
    
    // 评分分布数据
    const ratingDistribution = ref([]);
    // 页面加载状态
    const isLoading = ref(true);
    // 图表加载状态
    const chartLoading = ref(false);
    // 图表类型（依据分析store中的filter.chartType）
    const chartType = computed(() => {
      // 将store中的chartType转换为qiun-data-charts支持的类型
      switch(analysisStore.filter.chartType) {
        case 'bar': return 'column';
        case 'pie': return 'pie';
        default: return 'column';
      }
    });
    
    // 图表数据对象
    const chartDataObject = computed(() => {
      // 如果没有评分数据，返回空数据结构
      if (!ratingDistribution.value || ratingDistribution.value.length === 0) {
        return {
          categories: [],
          series: []
        };
      }
      
      // 准备图表数据
      const result = {};
      
      // 根据图表类型处理数据格式
      if (chartType.value === 'pie') {
        // 饼图不需要categories，直接构建rating为name，count为data的数据
        result.series = ratingDistribution.value.map(item => ({
          name: `${item.rating}星`,
          data: item.count
        }));
      } else {
        // 柱状图需要categories和series
        // 设置分类（评分等级）
        result.categories = ratingDistribution.value.map(item => `${item.rating}星`);
        
        // 构建系列数据
        result.series = [{
          name: '评分数量',
          data: ratingDistribution.value.map(item => item.count)
        }];
      }
      
      return result;
    });
    // 图表类型
    const chartTypes = [
      { label: '柱状图', value: 'bar', icon: 'icon-bar-chart' },
      { label: '饼图', value: 'pie', icon: 'icon-pie-chart' }
    ];
    // 加载文字
    const loadingText = {
      contentdown: '上拉显示更多',
      contentrefresh: '数据加载中...',
      contentnomore: '没有更多数据了'
    };
    
    // 计算评分总数
    const totalRatings = computed(() => {
      if (!ratingDistribution.value || ratingDistribution.value.length === 0) return 0;
      return ratingDistribution.value.reduce((total, item) => total + item.count, 0);
    });
    
    // 计算平均评分
    const averageRating = computed(() => {
      if (!ratingDistribution.value || ratingDistribution.value.length === 0) return '0.0';
      
      // 计算加权平均分
      let totalScore = 0;
      let totalCount = 0;
      
      ratingDistribution.value.forEach(item => {
        totalScore += item.rating * item.count;
        totalCount += item.count;
      });
      
      return totalCount > 0 ? (totalScore / totalCount).toFixed(1) : '0.0';
    });
    
    // 获取比例最高的评分
    const highestRating = computed(() => {
      if (!ratingDistribution.value || ratingDistribution.value.length === 0) return 0;
      
      // 找出最高比例的评分
      let highestItem = ratingDistribution.value[0];
      
      ratingDistribution.value.forEach(item => {
        if (item.percentage > highestItem.percentage) {
          highestItem = item;
        }
      });
      
      return highestItem.rating;
    });
    
    // 计算最高评分的百分比
    const highestRatingPercentage = computed(() => {
      if (!ratingDistribution.value || ratingDistribution.value.length === 0) return 0;
      
      // 找出最高比例的评分
      let highestPercentage = 0;
      
      ratingDistribution.value.forEach(item => {
        if (item.percentage > highestPercentage) {
          highestPercentage = item.percentage;
        }
      });
      
      return (highestPercentage * 100).toFixed(1);
    });
    
    // 页面初始化
    onMounted(() => {
      loadRatingDistribution();
    });
    
    // 加载评分分布数据
    async function loadRatingDistribution() {
      isLoading.value = true;
      try {
        // 获取评分分布数据
        const data = await analysisStore.fetchRatingDistribution();
        // 确保数据是按照评分从高到低排序的
        ratingDistribution.value = (data || []).sort((a, b) => b.rating - a.rating);
      } catch (error) {
        console.error('加载评分分布数据失败:', error);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      } finally {
        isLoading.value = false;
      }
    }
    
    // 切换图表类型
    function switchChartType(type) {
      analysisStore.setFilter({ chartType: type });
      // 图表类型改变后会自动触发图表重绘，因为我们使用了computed
    }
    
    // 刷新数据
    function refreshData() {
      loadRatingDistribution();
    }
    
    // 导出数据
    function exportData() {
      const csvContent = analysisStore.exportToCSV('rating');
      
      // 在真实环境中，这里会处理CSV导出
      // 由于小程序和H5环境的限制，这里只做简单提示
      uni.showModal({
        title: '导出成功',
        content: '在实际环境中，这里会下载评分分布数据的CSV文件',
        showCancel: false
      });
      
      console.log('导出的CSV数据：', csvContent);
    }
    
    return {
      analysisStore,
      chartTypes,
      loadingText,
      ratingDistribution,
      isLoading,
      chartLoading,
      chartType,
      chartDataObject,
      totalRatings,
      averageRating,
      highestRating,
      highestRatingPercentage,
      switchChartType,
      refreshData,
      exportData
    };
  }
};
</script>

<style lang="scss">
.rating-distribution-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 30rpx;
  
  /* 顶部标题样式 */
  .header {
    margin-bottom: 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
    }
    
    .subtitle {
      font-size: 24rpx;
      color: #999999;
      margin-top: 10rpx;
    }
  }
  
  /* 操作栏样式 */
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .chart-type-switcher {
      display: flex;
      
      .type-item {
        display: flex;
        align-items: center;
        margin-right: 30rpx;
        font-size: 26rpx;
        color: #666666;
        
        .iconfont {
          margin-right: 6rpx;
          font-size: 28rpx;
        }
        
        &.active {
          color: #0066ff;
          font-weight: 500;
        }
      }
    }
  }
  
  /* 评分总览卡片样式 */
  .overview-card {
    display: flex;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .overview-item {
      flex: 1;
      text-align: center;
      padding: 0 20rpx;
      position: relative;
      
      &:not(:last-child):after {
        content: '';
        position: absolute;
        right: 0;
        top: 20%;
        height: 60%;
        width: 1px;
        background-color: #f0f0f0;
      }
      
      .item-value {
        font-size: 40rpx;
        color: #0066ff;
        font-weight: bold;
        display: block;
      }
      
      .item-label {
        font-size: 24rpx;
        color: #999999;
        margin-top: 10rpx;
        display: block;
      }
    }
  }
  
  /* 图表区域样式 */
  .chart-area {
    background-color: #ffffff;
    border-radius: 12rpx;
    margin-bottom: 30rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }
  
  /* 加载状态样式 */
  .loading-container {
    padding: 40rpx 0;
  }
  
  /* 评分列表样式 */
  .rating-list {
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .section-title {
      font-size: 30rpx;
      font-weight: 500;
      color: #333333;
      margin-bottom: 30rpx;
    }
    
    .rating-item {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      
      .rating-stars {
        width: 160rpx;
        display: flex;
        align-items: center;
        
        .star-value {
          font-size: 30rpx;
          font-weight: 500;
          color: #333333;
          margin-right: 6rpx;
        }
        
        .star-label {
          font-size: 22rpx;
          color: #999999;
          margin-right: 10rpx;
        }
      }
      
      .rating-bar {
        flex: 1;
        height: 24rpx;
        background-color: #f0f0f0;
        border-radius: 12rpx;
        margin: 0 20rpx;
        overflow: hidden;
        
        .rating-progress {
          height: 100%;
          background-color: #ff9900;
          border-radius: 12rpx;
          min-width: 2%;
        }
      }
      
      .rating-info {
        width: 140rpx;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        
        .rating-count {
          font-size: 26rpx;
          color: #333333;
          font-weight: 500;
        }
        
        .rating-percentage {
          font-size: 22rpx;
          color: #999999;
          margin-top: 4rpx;
        }
      }
    }
    
    .no-data {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
      color: #999999;
      font-size: 26rpx;
    }
  }
  
  /* 底部操作区样式 */
  .footer-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
    
    .action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48%;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      
      .iconfont {
        margin-right: 10rpx;
      }
      
      &.export-btn {
        background-color: #ffffff;
        color: #0066ff;
        border: 1px solid #0066ff;
      }
      
      &.refresh-btn {
        background-color: #0066ff;
        color: #ffffff;
      }
    }
  }
}
</style>
